package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.client.article.IArticleClient;
import com.heima.client.user.IApUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.BaiduScanService;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticleConfig;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Lijx
 * @Date 2024-08-01 21:36
 */
@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IApUserClient apUserClient;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private BaiduScanService baiduScanService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 加载回复评论列表
     * @param commentId
     * @param minDate
     * @return
     */
    @Override
    public ResponseResult getCommentRepayList(String commentId, Object minDate) {
        Date date = null;

        //判断参数类型是哪种格式
        if (minDate instanceof Long) {
            Long time = (Long) minDate;
            //转换为data日期格式
            date = new Date(time);
        }else if (minDate instanceof Date) {
            date = (Date) minDate;
        }

        //查询回复评论列表
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(Query.query(Criteria.where("commentId").is(commentId)
                                .and("createdTime").lte(date))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                        .limit(10),
                ApCommentRepay.class);

        //判断当前文章是否有评论
        if (commentRepayList != null && commentRepayList.size() >0) {
            //查询当前登录用户，是否点赞评论
            Integer userId = ApThreadLocalUtil.get();
            if (userId != null && userId != 0 ) {
                List<ApCommentRepayLike> commentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("authorId").is(userId)),
                        ApCommentRepayLike.class);
                //通过stream流收集评论id
                if (commentRepayLikes != null && commentRepayLikes.size() >0) {
                    List<String> list = commentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());
                    //遍历集合
                    for (String commentRepayId : list) {
                        for (ApCommentRepay commentRepay : commentRepayList) {
                            if (commentRepay.getId().equals(commentRepayId)) {
                                commentRepay.setOperation(0);
                            }
                        }
                    }
                }
            }
        }

        return ResponseResult.okResult(commentRepayList);
    }

    /**
     * 保存回复评论
     * @param commentId
     * @param content
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(String commentId, String content) {
        //验证用户是否登录
        // 如果id无效，或者是0(游客)：流程结束
        Integer userId = ApThreadLocalUtil.get();
        if (userId == null || userId == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        //查询该评论属于哪个文章
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentId)),
                ApComment.class);

        //查询文章配置信息，是否允许评论
        ResponseResult configInfo = articleClient.getArticleConfig(apComment.getEntryId());
        if (configInfo.getCode() != 200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApArticleConfig articleConfig = JSON.parseObject(JSON.toJSONString(configInfo.getData()), ApArticleConfig.class);
        //如果不允许评论
        if (!articleConfig.getIsComment()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //查询登录用户信息
        ResponseResult userInfo = apUserClient.getUserInfo(userId);
        if (userInfo.getCode() != 200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        ApUser user = JSON.parseObject(JSON.toJSONString(userInfo.getData()), ApUser.class);

        //评论内容不能超过140字
        if (content.length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //验证发布的评论是否合规
        boolean res = baiduScanService.scanText(content);
        if (!res) { //不合格
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApCommentRepay commentRepay = new ApCommentRepay();
        commentRepay.setCommentId(commentId);
        commentRepay.setContent(content);
        commentRepay.setAuthorId(userId);
        commentRepay.setLikes(0);
        commentRepay.setAuthorName(user.getName());
        commentRepay.setCreatedTime(new Date());
        commentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(commentRepay);

        //发送消息
        kafkaTemplate.send("article_comment",JSON.toJSONString(apComment.getEntryId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 回复评论点赞
     * @param commentRepayId
     * @param operation
     * @return
     */
    @Override
    public ResponseResult commentRepayLike(String commentRepayId, Integer operation) {
        //验证用户是否登录
        // 如果id无效，或者是0(游客)：流程结束
        Integer userId = ApThreadLocalUtil.get();
        if (userId == null || userId == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        //查询这条评论数据
        ApCommentRepay commentRepay = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentRepayId)),
                ApCommentRepay.class);
        if (commentRepay == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断是点赞还是取消点赞
        if (operation == 0) { //0表示点赞
            Integer likes = commentRepay.getLikes();
            commentRepay.setLikes(likes+1);
            commentRepay.setUpdatedTime(new Date());
            //重新更新保存评论信息
            mongoTemplate.save(commentRepay);

            //记录当前用户对于当前评论的数据
            ApCommentRepayLike commentRepayLike = new ApCommentRepayLike();
            commentRepayLike.setCommentRepayId(commentRepayId);
            commentRepayLike.setAuthorId(userId);
            mongoTemplate.save(commentRepayLike);
        }else { //取消点赞
            Integer likes = commentRepay.getLikes();
            commentRepay.setLikes(likes-1);
            commentRepay.setUpdatedTime(new Date());
            //重新更新保存评论信息
            mongoTemplate.save(commentRepay);

            //删除当前用户对于当前评论的数据
            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").is(commentRepayId)
                            .and("authorId").is(userId)),
                    ApCommentRepayLike.class);
        }

        return ResponseResult.okResult(commentRepay.getLikes());
    }
}
